package com.android.love.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;

/**
 * 监听网络状态变化，当网络连接开启或关闭时将调用回调函数。 
 * 需创建一个实例,同时在onCreate()和onResume方法中调用 bind(this)
 * 在onPause方法调用unbind()
 * 
 * @author adison
 * 
 */
public class ConnectivityReceiver extends BroadcastReceiver {

	// 实现OnNetworkAvailableListener接口，网络状态变化时会得到通知。
	public static interface OnNetworkAvailableListener {
		public void onNetworkAvailable();

		public void onNetworkUnavailable();
	}

	private final ConnectivityManager connectivityManager;
	private OnNetworkAvailableListener onNetworkAvailableListener;
	private boolean connection = false;

	public ConnectivityReceiver(Context context) {
		connectivityManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		checkConnectionOnDemand();
	}

	public void bind(Context context) {
		IntentFilter filter = new IntentFilter();
		filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
		context.registerReceiver(this, filter);
		checkConnectionOnDemand();
		if (context instanceof OnNetworkAvailableListener)
			setOnNetworkAvailableListener((OnNetworkAvailableListener) context);
	}

	public void unbind(Context context) {
		context.unregisterReceiver(this);
	}

	/**
	 * 检查网络
	 */
	private void checkConnectionOnDemand() {
		final NetworkInfo info = connectivityManager.getActiveNetworkInfo();
		if (info == null || info.getState() != State.CONNECTED) {
			if (connection == true) {
				connection = false;
				if (onNetworkAvailableListener != null)
					onNetworkAvailableListener.onNetworkUnavailable();
			}
		} else {
			if (connection == false) {
				connection = true;
				if (onNetworkAvailableListener != null)
					onNetworkAvailableListener.onNetworkAvailable();
			}
		}
	}

	@Override
	public void onReceive(Context context, Intent intent) {
		if (connection == true
				&& intent.getBooleanExtra(
						ConnectivityManager.EXTRA_NO_CONNECTIVITY, false)) {
			connection = false;
			if (onNetworkAvailableListener != null) {
				onNetworkAvailableListener.onNetworkUnavailable();
			}
		} else if (connection == false
				&& !intent.getBooleanExtra(
						ConnectivityManager.EXTRA_NO_CONNECTIVITY, false)) {
			connection = true;
			if (onNetworkAvailableListener != null) {
				onNetworkAvailableListener.onNetworkAvailable();
			}
		}
	}

	/**
	 * 检查网络状态
	 * 
	 * @return
	 */
	public boolean hasConnection() {
		return connection;
	}

	public void setOnNetworkAvailableListener(
			OnNetworkAvailableListener listener) {
		this.onNetworkAvailableListener = listener;
	}

}
